package com.aebiz.usercenter.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.aebiz.usercenter.auth.pojo.ARoleMenu;
import com.aebiz.usercenter.auth.service.IAuthService;
import com.aebiz.usercenter.common.util.ConstatFinalUtil;
import com.aebiz.usercenter.users.pojo.AAdmins;

@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter{

	@Resource
	private IAuthService authService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String info="";
		/*验证是否登录*/
		HttpSession session=request.getSession();
		AAdmins aAdmins=(AAdmins) session.getAttribute("admins");
		if(aAdmins==null){
			/* 非法访问,请先登陆 */
			info=ConstatFinalUtil.INFO_JSON.getString("7");
			session.setAttribute("info", info);
			response.sendRedirect(request.getContextPath()+"login.htm");
			return false;
		}
		String currURl=request.getRequestURI()+"";
		System.out.println(currURl);
		/*完整路径*/
		ConstatFinalUtil.SYS_LOGGER.info("getRequestURL完整路径:{}",request.getRequestURL()+"");
		/*相对路径*/
		ConstatFinalUtil.SYS_LOGGER.info("getRequestURI相对路径:{}",request.getRequestURI()+"");
		
		/*查询角色对应的菜单*/
		Map< String, Object> condMap=new HashMap<>();
		condMap.put("roleId", aAdmins.getRoleId());
		Map<String, Object> resultMap=this.authService.findCondListRoleMenuService(null, condMap);
		List<ARoleMenu> roleMenuList=(List<ARoleMenu>) resultMap.get("list");
		for (Iterator iterator = roleMenuList.iterator(); iterator.hasNext();) {
			ARoleMenu aRoleMenu = (ARoleMenu) iterator.next();
			if(currURl.indexOf(aRoleMenu.getMenu().getUrl())!=-1){
				return true;
			}
		}
		
		response.sendRedirect(request.getContextPath() + "/info/error.jsp");
		return false ; 
	}
	
	
}
